package com.example.demo.leetcode;

/**
 * 链接：<a href="https://leetcode.cn/problems/search-a-2d-matrix/description/?envType=study-plan-v2&envId=top-interview-150">https://leetcode.cn/problems/search-a-2d-matrix/description/?envType=study-plan-v2&envId=top-interview-150</a>
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/02/19 14:00
 */
public class _74_搜索二维矩阵 {

    public static void main(String[] args) {
        int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
        int target = 13;
        int[][] matrix1 = {{1, 3}};
        int target1 = 3;
        boolean b = searchMatrix(matrix1, target1);
        System.out.println(b);
    }

    public static boolean searchMatrix(int[][] matrix, int target) {
        int length = matrix.length;

        int left = 0;
        int right = length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int[] arr = matrix[mid];
            if (arr[0] > target) {
                right = mid - 1;
            } else if (arr[arr.length - 1] < target) {
                left = mid + 1;
            } else if (arr[0] <= target && arr[arr.length - 1] >= target) {
                return search(arr, target);
            }
        }
        return false;
    }

    public static boolean search(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return true;
            } else if (arr[mid] > target) {
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            }
        }
        return false;
    }


}
